const { File } = require("ada-util");
const Path = require("path");
const classPropertiesPollyfill = require("../pollyfills/class-properties");

module.exports = function ({ content, path, option, fileInfo }) {
    content = content.replace(/import\(.*?\)/g, (str) => `_import(${str.substring(7, str.length - 1)})`);
    const babel = require(Path.resolve(option.nmodulePath, './@babel/core'));
    return new Promise((resolve, reject) => {
        try {
            if (option.develop) {
                if (option.sourcemap) {
                    let filename = fileInfo.required;
                    let info = babel.transform(content, Object.assign({
                        filename,
                        sourceMaps: true
                    }, option.compiler.babel));
                    info.map.sources = [`${option.siteURL + filename}`];
                    info.map.sourcesContent = info.map.sourcesContent.map(a => `\n${a}`);
                    content = info.code;
                    content = classPropertiesPollyfill(content);
                    content = content + `\n//# sourceMappingURL=${option.siteURL}${filename}.map`;
                    new File(Path.resolve(option.distPath, `./${filename}.map`)).write(JSON.stringify(info.map)).then(() => {
                        resolve(content);
                    });
                } else {
                    let ops = Object.assign({}, option.compiler.babel, { filename: path });
                    content = babel.transform(content, ops).code;
                    content = classPropertiesPollyfill(content);
                    resolve(content);
                }
            } else {
                let ops = Object.assign({}, option.compiler.babel, { filename: path });
                content = babel.transform(content, ops).code;
                content = classPropertiesPollyfill(content);
                resolve(content);
            }
        } catch (e) {
            reject(e);
        }
    });
};